using System.Net.Http.Headers;
using Blazored.LocalStorage;
using StudentVideo.Client.Common.Constants;

namespace StudentVideo.Client.Handler;

public class BearerTokenHandler(ILocalStorageService localStorage, ILogger<BearerTokenHandler> logger): DelegatingHandler {
   private readonly ILocalStorageService _localStorage = localStorage;
   private readonly ILogger<BearerTokenHandler> _logger = logger;

   // 改为 readonly 数组
   private static readonly string[] ExcludePaths = [
        "/api/login/admin",
        "/api/login/student",
        "/api/login/reloadToken"
   ];

   protected override async Task<HttpResponseMessage> SendAsync(
       HttpRequestMessage request,
       CancellationToken cancellationToken) {
      if (OperatingSystem.IsBrowser()) {
         try {
            var token = await _localStorage.GetItemAsync<string>(
                LocalStorageKeys.Token,
                cancellationToken);

            // 更精确的路径匹配
            var requestPath = request.RequestUri?.AbsolutePath ?? string.Empty;
            var shouldSkip = ExcludePaths.Any(path =>
                requestPath.Equals(path, StringComparison.OrdinalIgnoreCase));

            if (!string.IsNullOrWhiteSpace(token) && !shouldSkip) {
               request.Headers.Authorization =
                   new AuthenticationHeaderValue("Bearer", token.Trim());
            }
         } catch (Exception ex) {
            _logger.LogWarning("Error accessing local storage: {message}", ex.Message);
         }
      }

      return await base.SendAsync(request, cancellationToken);
   }
}
